package com.mocai.merchant.core.domain;

import com.mocai.merchant.core.ReflectionUtils;
import com.mocai.merchant.core.domain.annotation.Column;
import com.mocai.merchant.core.domain.annotation.Table;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/19.
 */
public class ColumnMapping {

    private String table;
    private String id;
    private String sort;
    private String parent;
    private String path;

    /**
     * 获取实体类的列信息
     *
     * @param cls
     * @return
     */
    public static ColumnMapping get(Class cls) {
        Method[] methods = ColumnMapping.class.getDeclaredMethods();
        List<String> methodNames = new ArrayList<>();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get")) {
                methodNames.add(name);
            }
        }

        ColumnMapping returnValue = new ColumnMapping();
        // 表名
        Table tableAnnotation = (Table) cls.getAnnotation(Table.class);
        if (null != tableAnnotation) {
            returnValue.setTable(tableAnnotation.name());
        } else {
            returnValue.setTable(ReflectionUtils.toColumn(cls.getSimpleName()));
        }
        // 字段名
        for (Method method : cls.getMethods()) {
            String name = method.getName();
            if (methodNames.contains(name)) {
                Column columnAnnotation = method.getAnnotation(Column.class);
                try {
                    String fieldName = ReflectionUtils.toFieldName(name);
                    Field field = ColumnMapping.class.getDeclaredField(fieldName);
                    if (null != columnAnnotation) {
                        field.set(returnValue, columnAnnotation.name());
                    } else {
                        field.set(returnValue, field.getName());
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return returnValue;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getParent() {
        return parent;
    }

    public void setParent(String parent) {
        this.parent = parent;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }
}
